<?php


namespace app\plugin\controller\draw_logic;


use app\common\controller\AppCommon;
use app\plugin\controller\draw_logic\com\DrawLogic;
use app\plugin\controller\draw_logic\model\PluginDrawLogic;
use app\service\Page;

class Manager extends DrawLogic
{
    public function index()
    {
        $where = [];
        $keyword = !empty($this->param['keyword']) ? trim($this->param['keyword']) : '';
        $orderBy = 'id desc';
        if (!empty($keyword)) {
            $where['title'] = ['like', '%' . $keyword . '%'];
        }
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $pageSize = 10;

        $data = AppCommon::data_list('plugin_draw_logic', $where, $page . ',' . $pageSize, '', $orderBy);

        $total = AppCommon::data_count('plugin_draw_logic', $where);

        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function form()
    {
        $key = !empty($this->param['key']) ? trim($this->param['key']) : '';
        if (!empty($key)) {
            $data = AppCommon::data_get('plugin_draw_logic', ['key' => $key]);
            $this->assign('data', $data);
        }
        return $this->fetch();
    }

    public function action()
    {
        $model = new PluginDrawLogic();
        $key = !empty($this->param['key']) ? trim($this->param['key']) : '';
        $ac = !empty($this->param['ac']) ? trim($this->param['ac']) : '';
        if (!empty($key)) {
            $data = AppCommon::data_get('plugin_draw_logic', ['key' => $key], 'key');
            if (empty($data)) {
                data_return('数据未找到', -1);
            }
        }
        if ($ac == 'del') {
            $model->where(['key' => $key])->delete();
            data_return('删除成功');
        } elseif ($ac == 'copy') {
            $data = $model->where(['key' => $key])->find();
            $model->save([
                'title' => $data['title'] . '|copy',
                'content' => $data['content'],
                'key' => $this->get_key(10)
            ]);
            data_return('复制成功');
        }
        if (empty($this->param['title'])) {
            data_return('标题必填', -1);
        } elseif (empty($this->param['content'])) {
            data_return('内容必填', -1);
        }
        $insertData = [
            'title' => $this->param['title'],
            'content' => $this->param['content']
        ];

        if (empty($data)) {
            $insertData['key'] = $this->get_key(10);
            $model->save($insertData);
        } else {
            $model->save($insertData, ['key' => $key]);
        }
        data_return('数据保存成功');
    }

}